var network = {
	http : Ti.Network.createHTTPClient({
		validatesSecureCertificate:false,
		timeout:10000
	}),
	
	getServerDataWithHandlers: function (url,onResponseOkHandler,onResponseKoHandler){
		if(Ti.Network.networkType == Ti.Network.NETWORK_NONE){
			var alertDialog = Titanium.UI.createAlertDialog({
				title: L('WARNING'),
				message: L('Your device is not online.'),
				buttonNames: ['OK']
	        });
			Ti.App.fireEvent(onResponseKoHandler,{status:'no network'});
			alertDialog.show();
		    return;
		}
		
		Ti.API.info("getServerDataWithHandlers called");		
		var url_get = url;
		this.http.shouldUseRFC2616RedirectBehaviour = false;
		this.http.shouldRedirect = false;
		
		this.http.open('GET',url_get);
		this.http.setRequestHeader('referer',url_get);
		this.http.onerror = function(e){
			Ti.App.fireEvent(onResponseKoHandler,e.error);
		};
		
		this.http.onload = function(e){
			if(this.status == 200){	
				Ti.App.fireEvent(onResponseOkHandler,{text:this.responseText});
			}else{					
				Ti.App.fireEvent(onResponseKoHandler,{status:this.status});
			}
		};
		
		this.http.send();
	},
	
	getTorrents : function (){
		Ti.API.info("getTorrents called");	
		this.getServerDataWithHandlers(Ti.App.config.url_torrents_gae,'torrentDownloadOk','torrentDownloadKo');
	},

	getComentaris : function (idIdea){
		Ti.API.info("getComentaris called");
		this.getServerDataWithHandlers(Ti.App.config.url_torrents_comentaris_gae + idIdea,'comentarisDownloadOk','comentarisDownloadKo');
	}
};

network.getCookieValue= function (getCookieValue_str){
	Ti.API.info("text inicial:" + getCookieValue_str);
	var getCookieValue_cookie = getCookieValue_str.substr(-104,69);
	//Ti.API.info("text parsed:" + getCookieValue_cookie);
	var getCookieValue_array = getCookieValue_cookie.split("=");
	
	//Ti.API.info("parsed length:" + getCookieValue_array.length);
	//Ti.API.info("parsed length0:" + getCookieValue_array[0].length);
	//Ti.API.info("parsed length1:" + getCookieValue_array[1].length);
	if(getCookieValue_array.length == 2 && getCookieValue_array[0].length==36 && getCookieValue_array[1].length == 32){
		Ti.API.info("cookie parsed ok");
		cookie_string = getCookieValue_cookie;
		//cookie.name = getCookieValue_array[0];
		//cookie.value = getCookieValue_array[1];	
	}else{
		Ti.API.info("cookie parsed ko");
		cookie_string = '';
	}
	Ti.App.Properties.setString("cookie_sessio",cookie_string);
	Ti.API.info("contenido de cookie:" + cookie_string);
	return cookie_string;
};

network.getTokenFromWeb = function(user,password,webview){
	Ti.API.info("getToken called");
	
	var url_post = Ti.App.config.url_ideatorrent +"?destination=ideatorrent";
	var post_data = {
		"name":user,
		"pass":password,
		"op":'Entra',
		'form_id':'user_login_block'
	};
	//this.http.useSessionPersistence = true;
	//this.http.useKeychainPersistence = true;
	this.http.shouldUseRFC2616RedirectBehaviour = false;
	this.http.shouldRedirect = false;
	
	this.http.open('POST',url_post);
	if(cookie_string != ''){
		Ti.API.info("we add cookie");
		this.http.setRequestHeader("Cookie", cookie_string);
	}
	this.http.setRequestHeader('referer',url_post);

	this.http.onerror = function(e){Ti.API.info("ERROR " + e.error);};
	
	this.http.onload = function()
	{
		if (this.status == 302){
			var cookieStr = this.getResponseHeader("Set-Cookie");
			
			//Ti.API.info("cookie:"+cookie);
			var cookieObj = network.getCookieValue(cookieStr);
			//text inicial:
			//SESSb722d8b547ee528a5cae6af3103e40e3=deleted; expires=Sat, 06-Mar-2010 18:31:25 GMT; path=/, SESSb722d8b547ee528a5cae6af3103e40e3=e2e6a440c079d62059259a8d6057bfbc; path=/; domain=.xifrat.pirata.cat
			//SESSb722d8b547ee528a5cae6af3103e40e3=6c85dfa2ec810a1e9180d1af3bbc950f; path=/; domain=.xifrat.pirata.cat, SESSb722d8b547ee528a5cae6af3103e40e3=dc6a663fb0d1fedb63ac34d2e07a1540; path=/; domain=.xifrat.pirata.cat
		}else{
			if(this.status == 200){
				if (this.responseText.search("Ho sentim, el nom d'usuari o la contrasenya no s") == -1){
					Ti.API.info("RESULTADO OK");
					webview.html="RESULTADO OK";
				}else{
					Ti.API.info("RESULTADO KO");
					webview.html="RESULTADO KO";
				}
			}
		}
		Ti.API.info("User agent: " + Ti.App.config.user_agent);
	    Ti.API.info("Loaded! Status: " + this.status);
	    var contentType = this.getResponseHeader('Content-Type');
	    Ti.API.info("Content-Type: " + contentType);
		//var cookie2 = ;
		//Ti.API.info("cookie:"+ this.getResponseHeader("Set-Cookie"));
		var location = this.getResponseHeader("Location");
		Ti.API.info("location:"+location);
		//Ti.API.info(this.responseText);
	};
	
	
	// send the data
	this.http.send(post_data);
};

network.checkSession = function(webview){
	Ti.API.info("checkSession called");	
	
	if(cookie_string==''){ 
		return false;
	}
	
	var url_get = Ti.App.config.url_profile;
	this.http.shouldUseRFC2616RedirectBehaviour = false;
	this.http.shouldRedirect = false;
	
	this.http.open('GET',url_get);
	Ti.API.info("we add cookie:"+cookie_string);
	this.http.setRequestHeader("Cookie", cookie.string);
	this.http.setRequestHeader('referer',url_get);

	this.http.onerror = function(e){Ti.API.info("ERROR " + e.error);};
	
	this.http.onload = function()
	{
		if (this.status == 302){
			var cookieStr = this.getResponseHeader("Set-Cookie");
			var cookieObj = network.getCookieValue(cookieStr);
		}else{
			if(this.status == 200){
				if (this.responseText.search("Ho sentim, el nom d'usuari o la contrasenya no s") == -1){
					Ti.API.info("RESULTADO OK");
					webview.html="RESULTADO OK";
				}else{
					Ti.API.info("RESULTADO KO");
					webview.html="RESULTADO KO";
				}
			}
		}
	};
	
	this.http.send();
};
